package edu.mobbuzz.web.pages;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;

import edu.mobbuzz.daf.bean.User;
import edu.mobbuzz.web.base.SecureBasePage;
import edu.mobbuzz.web.encoder.StringValueEncoder;
import edu.mobbuzz.web.facade.ManagementFacade;
import edu.mobbuzz.web.model.StatusSelectionModel;

public class UserFormPage extends SecureBasePage{
	@Property
	private User user;
	@Component
	private Form userForm;
	private ManagementFacade managamentFacade;
	
	private String username;
	private List<String> statusList;
	
	
	public List<String> getStatusList() {
		if(statusList==null){
			statusList = new ArrayList<String>();
			statusList.add("user");
			statusList.add("administrator");
		}
		return statusList;
	}

	public ManagementFacade getManagamentFacade() {
		if(managamentFacade==null)
			managamentFacade = new ManagementFacade();
		return managamentFacade;
	}

	void onActionFromClear(){
		user = null;
		userForm.clearErrors();
    }
	public StatusSelectionModel getStatusSelectionModel() {		
		return new StatusSelectionModel(getStatusList());
	}
	
	public ValueEncoder<Integer> getStatusValueEncoder(){
		return new StringValueEncoder();
	}
	
	Object onSuccessFromUserForm(){
		if(user.getUsername()==null){
			user.setStatus(0);	
			getManagamentFacade().addUser(user);
		}else{
			user.setStatus(0);	
			getManagamentFacade().updateUser(user);		
		}
		user = null;	
			
		return UserGridPage.class;
	}
	
	void onPrepare(){
    	if (user == null){
    		user = new User();
    	}
        
    }
    
    void cleanupRender() {
    	user = null;
	}
    
    void onActivate(String username){
		this.username = username;
		user = getManagamentFacade().getUserByPrimaryKey(username);	
	}
	
	String onPassivate(){ 
		return username;
	}	
}
